<?php

namespace app\admin\middleware;


use app\facade\Basic;
use app\admin\service\Token;

class Auth
{
    public function handle($request,\Closure $next){

        $request_rul = explode("?", $_SERVER['REQUEST_URI']);
        $request_rul = $request_rul[0];

        /* 跳过登录页面 */
        if(
            $request_rul === '/operator/account/login' ||
            $request_rul === '/operator/dingtalk/login' ||
            $request_rul === '/operator/dingtalk/callback' ||
            $request_rul === '/admin/LogisticsRules/export'  // 测试接口
        ){
            return $next($request);
        }

        // Token 不存在
        $token = $request->header('X-Token') ?? '68bda0b0dc52bba2d2028580851be5376f08cf80';

        if( empty($token) ) {
            return Basic::DataJson(401,'授权失效，Token不存在');
        }

        // 验证 Token
        $tokenObj = new Token();
        $obj = $tokenObj->check($token);


        if(is_null($obj)){
            return Basic::DataJson(401,'授权失效，Token失效');
        }

        $operator = json_decode($obj,true);
        $request->token = $token;
        $request->operator = $operator;
        $request->isadmin = $operator['isadmin'];
        $request->operator_id = $operator['operator_id'];
        $request->operator_user = $operator['cname'];
        $request->operator_roles = $operator['roles'];

        return $next($request);
    }

}
